package cn.letlet.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import cn.letlet.utils.Debug;

import cn.letlet.data.Data;

public class AiInterfaceHelper  extends Thread {
	
	//private static AiInterfaceHelper self = null;
	private  String libsoPath;
	private static AiInterface aiFace=AiInterface.getInstance();;
	
	public String getLibsoPath() {
		return libsoPath;
	}

	public void setLibsoPath(String libsoPath) {
		this.libsoPath = libsoPath;
	}

	public DataOutputStream outputStream;
	StreamGobbler errorGobbler;
	StreamGobbler outputGobbler;
	
	public void run() {
			initAiEngine();
		}
	
	public boolean initAiEngine() {
		Process process = null;
        try {
            process = Runtime.getRuntime().exec("./"+getLibsoPath());
            outputStream = new DataOutputStream(process.getOutputStream());
            outputStream.writeBytes("ucci\n");
            outputStream.flush();
            errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
			outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");
			errorGobbler.start();
			outputGobbler.start();
			process.waitFor();
        } catch (Exception e) {
            return false;
        }
        return true;
	}
	
	public void sendCommand(String paramString) {
		try {
			outputStream.writeBytes(paramString+"\n");
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	static class StreamGobbler extends Thread {
		InputStream is;
		String type;
		StreamGobbler(InputStream is, String type) {
			this.is = is;
			this.type = type;
		}
		InputStreamReader isr;
		BufferedReader br;
		public void run() {
			try {
				isr = new InputStreamReader(is);
				br = new BufferedReader(isr);
				String line = null;
				while ((line = br.readLine()) != null){
					String[] moveInfo = line.split(" ");
					if(moveInfo[0].equals("bestmove")){
						AiInterface.bestMove=moveInfo[1];
					}else if(moveInfo[0].equals("nobestmove")){
						AiInterface.bestMove=moveInfo[0];
					}
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		
		public void release(){
			try {
				//this.stop();
				is.close();
				isr.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void release(){
		try {
			errorGobbler.release();
			outputGobbler.release();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
